package com.tsinghua.discharge.common;

import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

@Component
//@WebFilter(urlPatterns = {"/upload/test.do"}, filterName = "tokenAuthorFilter")
public class TokenAuthorFilter implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse rep = (HttpServletResponse) response;

        req.setAttribute("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        req.setAttribute("Access-Control-Allow-Origin", "*");
        //设置允许跨域的配置
        // 这里填写你允许进行跨域的主机ip（正式上线时可以动态配置具体允许的域名和IP）
        //String[] allowDomain = {"http://218.199.33.75:9528", "http://218.199.33.77:9528"};
        //Set allowedOrigins = new HashSet(Arrays.asList(allowDomain));
        String originHeader = req.getHeader("Origin");
        //if (allowedOrigins.contains(originHeader)) {
            rep.setHeader("Access-Control-Allow-Origin", originHeader);//前台跨域IP
            rep.setHeader("Access-Control-Allow-Credentials", "true");
            // 允许的访问方法
            rep.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE, PATCH");

            // Access-Control-Max-Age 用于 CORS 相关配置的缓存
            rep.setHeader("Access-Control-Max-Age", "3600");
            rep.setHeader("Access-Control-Allow-Headers", "token,Origin, X-Requested-With,Access-Control-Allow-Origin , Content-Type, Accept");

            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            String token = req.getHeader("token");//header方式
            ServerResponse resultInfo;
            boolean isFilter = false;


            String method = ((HttpServletRequest) request).getMethod();
            if (method.equals("OPTIONS")) {
                rep.setStatus(HttpServletResponse.SC_OK);
            } else {
                if (null == token || token.isEmpty()) {
                    resultInfo = ServerResponse.createBySuccessMessage("用户授权认证没有通过!客户端请求参数中无token信息");
                } else {
                    if (TokenCache.getKey(token) != null) {
                        resultInfo = ServerResponse.createBySuccessMessage("用户授权认证通过!");
                        isFilter = true;
                    } else {
                        resultInfo = ServerResponse.createByErrorMessage("用户授权认证没有通过!客户端请求参数token信息无效");
                    }
                }
                if (!resultInfo.isSuccess()) {// 验证失败
                    PrintWriter writer = null;
                    OutputStreamWriter osw = null;
                    try {
                        osw = new OutputStreamWriter(response.getOutputStream(),
                                "UTF-8");
                        writer = new PrintWriter(osw, true);
                        String jsonStr = JSON.toJSONString(resultInfo);
                        writer.write(jsonStr);
                        writer.flush();
                        writer.close();
                        osw.close();
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        if (null != writer) {
                            writer.close();
                        }
                        if (null != osw) {
                            osw.close();
                        }
                    }
                    return;
                }
                if (isFilter) {
                    chain.doFilter(request, response);
                }
            //}
        }
    }
    @Override
    public void destroy() {

    }
}
